/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package it.unitn.science.matr155863_148346_145963.bccastestore.servlet;

import it.unitn.science.matr155863_148346_145963.bccastestore.DBManager;
import it.unitn.science.matr155863_148346_145963.bccastestore.items.User;
import it.unitn.science.matr155863_148346_145963.bccastestore.utils.MailSender;
import it.unitn.science.matr155863_148346_145963.bccastestore.utils.UserDetailsValidator;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Random;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.UnavailableException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import nl.captcha.Captcha;
import org.apache.log4j.Logger;

/**
 *
 * @author berto
 */
public class RegisterUserSRV extends HttpServlet {

    private DBManager db=null;
    private static Logger log = Logger.getLogger(RegisterUserSRV.class);
    
    @Override
    public void init(ServletConfig config) throws ServletException {
        super.init(config);
        try {
          db=(DBManager)super.getServletContext().getAttribute("db_manager");
        }catch(Exception e) {
            log.fatal(e);
            throw new UnavailableException(e.toString());
        }
    }
    
    private boolean isCorrectCaptcha(HttpServletRequest request){
        Captcha captcha = (Captcha) request.getSession().getAttribute(Captcha.NAME);
        String answer = request.getParameter("answer");
        if((captcha!=null)&&(answer!=null)&&(captcha.isCorrect(answer))) {
            //Correct
            return true;
        } else {
            //Incorrect
            return false;
        }
    }
    
    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        
        //Non va con: request.getContextPath()+
        
        //String mess="";
        //String errorOn=null;
        //String param="";
        boolean register=false;
        User user=null;
        //if(request.getParameter("register")!=null){
          if(isCorrectCaptcha(request)){
            try{
            user=UserDetailsValidator.createUser(request,true);
                try{                        
                    Random rd=new Random();
                    int code=rd.nextInt();
                    if(code>0){
                        code=-code;
                    }
                    user.setStatus(code);
                    user=db.registerUser(user);
                    /*request.setParameter("operation_message","Registration success!"
                          + "Under you can see the summary of the data");*/
                    //param=param+"om=0";
                    //user=db.authenticate(request.getParameter("email"),request.getParameter("password"));
                    if(user!=null){
                        String text="Welcome "+user.getUsername()+" to your Berto Casna Casagranda Aste Store:"+"\n"
                                +"\n"
                                +"Get Started Now"+"\n"
                                +"\n"
                                +"To complete the registration process, you need to click the registration link below"+"\n"
                                +"\n"
                                +"Complete Your Registration: "+"\n"
                                +"http://localhost:8084/"+request.getContextPath()+"/contents/public/activeUser"
                                + "?c="+code+"&r="+user.getRegister_at().getTime()
                                +"\n"+"\n";
                        //Devo generare un numero casuale perche' altrimenti dai dati un malitenzionato potrebbe capire il codice e aggirare la protezione
                        MailSender.sendTextMailWithAutentication("daghen.de.pu@gmail.com", "daghen.de.pu", "daghendepu@gmail.com", user.getEmail(), "BCCAStore confirm your registration", text);
                        register=true;
                        /*
                        request.getSession().setAttribute("user", user);
                        //Non va con: request.getContextPath()+
                        address=request.getContextPath()+"/contents/user/userDetails.jsp";
                    }else{*/
                        //mess="Unable to execute the registration!";
                        //errorOn=User.EMAIL;
                    }
                }catch(Exception ex){
                    request.setAttribute("om",ex.getMessage());
                    request.setAttribute("f",User.EMAIL);
                    //param="?om=2&f="+User.EMAIL;
                    //mess=ex.getMessage();
                    //errorOn=User.EMAIL;
                }
            }catch(Exception ex){
                //Error diuring operation
                request.setAttribute("om","Unable to execute the registration!");
                request.setAttribute("f",ex.getMessage());
                //param="?om=1&f="+ex.getMessage();
                //mess="Unable to execute the registration!";
                //errorOn=ex.getMessage();
            }
        }else{
                request.setAttribute("om","Unable to execute the registration!");
                request.setAttribute("f","Captcha");
                //param="?om=1&f=Unable to execute the registration!";
                //mess="Unable to execute the registration!";
                //errorOn="Captcha";
        }
        //}
        //response.sendRedirect(address+param);
        /*if(registered){
            
        }else{
            RequestDispatcher dispatcher =request.getRequestDispatcher(address);
            dispatcher.forward(request, response);
        }*/ 
        RequestDispatcher dispatcher;
        if(!register){
            //showForm;
            dispatcher =request.getRequestDispatcher("/contents/public/register.jsp");
        }else{
            //showDetails summaryRegistration
            dispatcher =request.getRequestDispatcher("/contents/public/summaryRegistration.jsp");
        }
        dispatcher.include(request, response);
    }
    
        
    

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
